Print a Christmas tree in JavaScript


Posted by Christy on 2023-01-20

Description: Write a function named tree that accepts an number n and print a Christmas tree with the following patterns

tree(1)
*

tree(5)
    *
   ***
  *****
 *******
*********
    *
    *
    *
    *
    *
function tree(n) {
  if (n === 1) return console.log("*");
  // tree
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - i) + "*".repeat(2 * i - 1));
  }

  // trunk
  for (let i = 1; i <= n; i++) {
    console.log(" ".repeat(n - 1) + "*");
  }
}

tree(5);









Related Posts

使用 AntV 製作資料圖表-台灣老年人口與長照機構供需比

使用 AntV 製作資料圖表-台灣老年人口與長照機構供需比

[ 學習筆記系列 ] 網頁本質 (一) - HTML 篇

[ 學習筆記系列 ] 網頁本質 (一) - HTML 篇

[Azure Pipeline Agent] Agent Pools vs Deployment Groups in Azure DevOps

[Azure Pipeline Agent] Agent Pools vs Deployment Groups in Azure DevOps


Comments